package com.xiaoban.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 小班哥
 * @version 1.0
 * @date 2023/9/22 20:59
 * @description 存储用户名、加密后的密码、用户权限等
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginSyUser implements UserDetails {

    private Users sysUser;

    //存储权限信息
    private List<String> permissions;

    public LoginSyUser(Users sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    //使用JSONField注解将该变量不被序列化存储到Redis中
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把permissions中的String类型的权限封装成SimpleGrantedAuthority对象，有两种方法实现 1、使用普通的for循环 2、使用stream
        //List<SimpleGrantedAuthority> newList =
        if (authorities != null){
            return authorities;
        }
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).
                        collect(Collectors.toList());
        //使用这种方式的话每一次调用框架内部都会执行一次，所以我们可以将集合设置为全局变量，
        // 当框架调用此方法是我们只需要判断全局变量中的值是否为空即可
        return authorities;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
